package com.hx.good.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hx.common.api.MiaoshaGoodsService;
import com.hx.common.api.OrderService;
import com.hx.common.domain.OrderInfo;
import com.hx.common.to.OrderMessageTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


/**
 * @Author wonghiu
 * @Date 2021/6/6 10:45
 * @Version 1.0.1
 * 监听回滚队列，完成回滚
 */
@Slf4j
@Component
//@RabbitListener(queues = "order.release.stock.queue")
@RabbitListener(queues = "order.callback.queue")
public class StockReleaseListener {
    @Reference(check = false)
    private OrderService orderService;
    @Reference(check = false)
    private MiaoshaGoodsService miaoshaGoodsService;

    @RabbitHandler
    @Transactional
    public void listener(OrderMessageTo orderMessageTo, Channel channel, Message message) throws IOException{
        try {
            log.info("收到解锁库存请求。。。");
            Long orderId = orderMessageTo.getOrderId();
            // TODO 不需要根据orderId，根据goodsId也可以解锁库存
            OrderInfo miaoshaOrder = orderService.getOrderById(orderId);
            // 只有订单状态小于等于2，才能够解锁
            if (miaoshaOrder.getStatus()<=2){
                miaoshaGoodsService.releaseStock(orderMessageTo);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }catch (Exception e){
//            System.out.println(e);
            // 解锁失败则让消息放回该队列，下次重新消费
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
